package com.zx.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.zx.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Component
public class ManagerFilter extends ZuulFilter {
    @Autowired
    private JwtUtil jwtUtil;

    @Override
    public String filterType() {
        return "pre";//请求之前过滤
    }

    @Override
    public int filterOrder() {
        return 1;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        System.out.println("进入后台网关过滤器.....");

        //管理员
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if(request.getMethod().equals("OPTIONS")){
            return null;
        }
        String url=request.getRequestURL().toString();
        if(url.indexOf("/admin/login")>0){
            System.out.println("登陆页面"+url);
            return null;
        }

        //先验证是否携带token   {"Authorization":"bearer token"}
        //先获取是否有指定key值的头信息
        String header = request.getHeader("Authorization");

        if(header == null || "".equals(header)){
            throw new RuntimeException("请先登录，权限不足");
        }else{
            if(header.startsWith("bearer ")||header.startsWith("Bearer ")){
                String token = header.substring(7);
                //解析token
                try {
                    Claims claims = jwtUtil.parseJWT(token);
                    String roles = (String) claims.get("roles");

                    if("超级用户".equals(roles)){

                        //将Authorization转发到下边微服务
                        currentContext.addZuulRequestHeader("Authorization",header);
                        System.out.println("token 验证通过，添加了头信息"+header);

                        return null;//放行处理
                    }else{
                        throw new RuntimeException("权限不足");
                    }
                }catch (Exception e){
                    e.printStackTrace();
                    throw new RuntimeException("令牌有误，权限不足！");
                }
            }else{
                throw new RuntimeException("令牌有误，权限不足！");
            }
        }
    }
}
